<script setup>
import { ref, computed, onUnmounted } from 'vue'

const now = ref(Date.now())

let timer

const formatTime = (time) => {
  return time < 10 ? `0${time}` : time
}

const localTime = computed(() => {
  const date = new Date(now.value) // 使用响应式时间戳
  return `${date.getFullYear()}-${formatTime(date.getMonth() + 1)}-${formatTime(date.getDate())} ${formatTime(date.getHours())}:${formatTime(date.getMinutes())}:${formatTime(date.getSeconds())}`
})

// 启动定时器
timer = setInterval(() => {
  now.value = Date.now() // 每秒更新时间戳
}, 1000)

// 组件卸载时清除定时器
onUnmounted(() => {
  clearInterval(timer)
})
</script>

<template>
  <div class="localTime">{{ localTime }}</div>
</template>

<style scoped lang="scss">
.localTime {
  position: absolute;
  bottom: 1vh;
  right: 1.5%;
  font-size: 0.9rem;
  color: #999;
  margin-left: 10px;
}
</style>
